<?php
/**
 *------------------------------------------------
 * Author: YYT[QQ:375776626]
 *------------------------------------------------
 */

class Crypt
{
    public $key; //密钥

    public $timeout; //解密超时(秒)

    public function __construct($key = '_YYTPHP_', $timeout = 60)
    {
        if (strlen($key) != 8) throw new Exception('密钥必须为8位');
        $this->key = $key;
        $this->timeout = $timeout;
    }

    public function encode($str)
    {
        if ($this->timeout > 0) $str = time().$str;
        $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
        $pad = $block - (strlen($str) % $block);
        $str = $str.str_repeat(chr($pad), $pad);
        return strtoupper(bin2hex(mcrypt_encrypt(MCRYPT_DES, $this->key, $str, MCRYPT_MODE_CBC, $this->key)));
    }

    public function decode($str)
    {
        $str = pack('H*', strtoupper($str));
        $str = mcrypt_decrypt(MCRYPT_DES, $this->key, $str, MCRYPT_MODE_CBC, $this->key);
        $block = mcrypt_get_block_size(MCRYPT_DES, MCRYPT_MODE_CBC);
        $pad = ord($str[($len = strlen($str)) - 1]);
        if (strspn($str, chr($pad), strlen($str) - $pad) != $pad) return false;
        $decode = substr($str, 0, strlen($str) - $pad);
        if ($this->timeout > 0) {
            if ((time() - substr($decode, 0, 10)) > $this->timeout) return false;
            $decode = substr($decode, 10);
        }
        return $decode;
    }
}